package com.knowledge.plus.创建线程and线程池.线程间隔离;

import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * ThreadLocal 线程间隔离（生命变量）
 *
 * @author PF.Tian
 * @since 2022/3/3
 */
public class ThreadLocalDemo implements Runnable {

    private static final ThreadLocal<SimpleDateFormat> TL_FORMATTER = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalDemo obj = new ThreadLocalDemo();
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(obj, "" + i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }
    }

    /**
     * 从输出中可以看出，Thread-0 已经改变了 TL_FORMATTER 的值，但仍然是 thread-2 默认格式化程序与初始化值相同，其他线程也一样。
     */
    @SneakyThrows
    @Override
    public void run() {
        System.out.println("Thread Name= " + Thread.currentThread().getName() + " 修改前 default Formatter = " + TL_FORMATTER.get().toPattern());

        Thread.sleep(new Random().nextInt(1000));

        // formatter pattern is changed here by thread, but it won't reflect to other threads
        TL_FORMATTER.set(new SimpleDateFormat("yyyy-MM-dd"));

        System.out.println("Thread Name= " + Thread.currentThread().getName() + " 修改后 formatter = " + TL_FORMATTER.get().toPattern());
    }

}

